package com.lehecai.ucenter.action.server;

import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.lehecai.core.service.memcached.MemcachedService;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreStringUtils;
import com.lehecai.ucenter.action.BaseAction;
import com.lehecai.ucenter.entity.permission.User;
import com.lehecai.ucenter.service.permission.UserService;
import com.lehecai.ucenter.utils.MemcachedTicket;

public class ChangePwdSubmitAction extends BaseAction {
	
	private static final long serialVersionUID = -8634484692576627642L;
	
	private MemcachedService memcachedService;
	private UserService userService;
	
	private String ticket;
	private String password;
	private String conPassword;
	
	public String handle() {
		if (StringUtils.isEmpty(ticket)) {
			logger.error("密码为空");
			super.setErrorMessage("ticket不能为空");
			return "failure";
		}
		if (StringUtils.isEmpty(password)) {
			logger.error("密码为空");
			super.setErrorMessage("密码不能为空");
			return "changePwd";
		}
		if (StringUtils.isEmpty(conPassword)) {
			logger.error("确认密码为空");
			super.setErrorMessage("确认密码不能为空");
			return "changePwd";
		}
		if (!(password).equals(conPassword)) {
			logger.error("两次密码输入不一致");
			super.setErrorMessage("两次密码输入不一致");
			return "changePwd";
		}
		MemcachedTicket memcachedTicket = null;
		try {
			memcachedTicket = (MemcachedTicket) memcachedService.get(ticket);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (memcachedTicket == null) {
			logger.error("修改密码未找到对应ticket信息，ticket可能已过期！");
			super.setErrorMessage("修改密码未找到对应ticket信息，ticket可能已过期，请重试！");
			return "failure";
		}
		User sUser = userService.get(Long.valueOf(memcachedTicket.getUid()));
		sUser.setPassword(CoreStringUtils.md5(password, CharsetConstant.CHARSET_UTF8));
		sUser.setUpdatedTime(new Date());
		userService.update(sUser);
		try {
			memcachedService.delete(ticket);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "success";
	}

	public String getTicket() {
		return ticket;
	}

	public void setTicket(String ticket) {
		this.ticket = ticket;
	}

	public MemcachedService getMemcachedService() {
		return memcachedService;
	}

	public void setMemcachedService(MemcachedService memcachedService) {
		this.memcachedService = memcachedService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getConPassword() {
		return conPassword;
	}

	public void setConPassword(String conPassword) {
		this.conPassword = conPassword;
	}
	
}
